import { check } from 'meteor/check';
import { JoinServer } from 'meteor-publish-join';
import { Friends } from '/imports/models/Friends';

/**
 * 获取用户好友列表
 * @param {Object} query
 * @param {Number} limit
 */
Meteor.publish('get.friends', function(query, limit) {
  check(query.user_id, String);
  check(limit, Number);

  const selector = {
    user_id: query.user_id,
  };

  const pipeline = [{
      $match: selector
    },
    {
      $lookup: {
        from: 'users',
        localField: 'friend_id',
        foreignField: '_id',
        as: 'infos'
      },
    },
    {
      $addFields: {
        info: {
          $arrayElemAt: ["$infos", 0]
        }
      }
    },
    {
      $project: {
        infos: 0,
        'info.services': 0
      }
    },
    {
      $limit: limit
    }
  ];

  JoinServer.publish({
    context: this,
    name: 'get.friends.counts',
    interval: 0,
    doJoin() {
      return Friends.find(selector).count();
    }
  });
  
  ReactiveAggregate(this, Friends, pipeline);
});
